package com.example.device.admin.web.config;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.iot.api.Profile;
import com.aliyun.openservices.iot.api.message.MessageClientFactory;
import com.aliyun.openservices.iot.api.message.api.MessageClient;
import com.aliyun.openservices.iot.api.message.callback.MessageCallback;
import com.aliyun.openservices.iot.api.message.entity.Message;
import com.aliyun.openservices.iot.api.message.entity.MessageToken;
//import com.example.device.admin.dao.entity.bo.DeviceStatusPost;
import com.example.device.admin.dao.entity.po.DeviceInfo;
import com.example.device.admin.service.DeviceInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @Configuration 配置类
 * @Value 将application.propertites配置文件的属性读出来
 * InitializingBean 在spring初始化bean的时候，如果bean实现了InitializingBean接口，会自动调用afterPropertiesSet方法。
 *
 * */
@Configuration
public class DeviceMessageRegister implements InitializingBean {
    @Value("${user.accessKeyID}")
    private String accessKey;

    @Value("${user.accessKeySecret}")
    private String accessSecret;

    @Value("${iot.regionId}")
    private String regionId;

    @Value("${user.uid}")
    private String uid;

    @Value("${iot.productKey}")
    private String productKey;

    @Autowired
    private Topic topic;




    @Autowired
    private DeviceInfoService deviceInfoService;



    private Logger logger = LoggerFactory.getLogger(getClass());



    @Override
    public void afterPropertiesSet() throws Exception {
        // endPoint:  https://${uid}.iot-as-http2.${region}.aliyuncs.com
        String endPoint = "https://" + uid + ".iot-as-http2." + regionId + ".aliyuncs.com";

        // 连接配置
        Profile profile = Profile.getAccessKeyProfile(endPoint, regionId, accessKey, accessSecret);

        // 构造客户端
        MessageClient client = MessageClientFactory.messageClient(profile);
        client.setMessageListener(new MessageCallback() {
            @Override
            public Action consume(MessageToken messageToken) {
                return null;
            }
        });

        //设备状态变化上报
        client.setMessageListener(topic.getDeviceStatusTopic(), new MessageCallback() {
            @Override
            public Action consume(MessageToken messageToken) {
                Message m = messageToken.getMessage();
                //logger.info("receive 设备状态变化上报" + new String(messageToken.getMessage().getPayload()));
                System.out.println(new String(messageToken.getMessage().getPayload()));
                DeviceInfo deviceInfo = JSON.parseObject(new String(m.getPayload()), DeviceInfo.class);

                String value = deviceInfo.getValue();
                String name = deviceInfo.getName();

                if (value == null || name == null) {
                    return Action.CommitFailure;
                }

                boolean b = deviceInfoService.updateStatus(name, value);

                if (b) {
                    return Action.CommitSuccess;
                }
                return Action.CommitFailure;

            }
        });

        // 数据接收
        client.connect(messageToken -> {
            Message m = messageToken.getMessage();
            byte[] payload = m.getPayload();
//            System.out.println("receive message from 从这里接受消息" + m);
//            System.out.println("m.getTopic() = 订阅" + m.getTopic());
            return MessageCallback.Action.CommitSuccess;
        });


    }
}
